var util = require('../../utils/util.js')
var url = util.baseUrl
//获取应用实例
var app = getApp()
var homedata = null;
var homedataDategory = null;

Page({
  data: {
    mdata: null,//主页显示内容
    movePosition: 'right: 32rpx; top: 70%',
    height: `height: ${app.globalData.deviceInfo.windowHeight}px;`,
    width: `width: ${app.globalData.deviceInfo.windowWidth}px;`,
    scrollY: true,
    homedataDategory: null,//12轮播图
    latitude: "",
    longitude: "",
    city: "",
    suitList: null,
    dataJson:""
  },

  onLoad: function (options) {
    console.log('这是首页');
    console.log(options);
    //获取到屏幕的宽高
    let screenWidth;
    let screenHeight;
    //获取屏幕宽度
    wx.getSystemInfo({
      success: function (res) {
        screenWidth = res.windowWidth
      }
    })
    //获取屏幕高度
    wx.getSystemInfo({
      success: function (res) {
        screenHeight = res.windowHeight
      }
    })

    console.log('屏幕高度:' + screenHeight)
    console.log('屏幕宽度:' + screenWidth)

    var that = this
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        console.log(latitude, longitude);
        that.loadCity(latitude, longitude);
      }
    })


    // wx.request({
    //     url: 'https://api.map.baidu.com/geocoder/v2/?ak=2XlpNCCDvGqSbYM3Csy70WF6ysUSiBsr&location=' + that.data.latitude + ',' + that.data.longitude + '&output=json',

    //     header: {
    //         'Content-Type': 'application/json'
    //     },
    //     success: function (res) {
    //         console.log(res);

    //         var city = res.data.result.addressComponent.city;
    //         // city = city.replace("市", "");
    //         that.setData({ city: city });
    //     }
    // });

    //获取首页所需的所有数据
    // util.request("/c2mwebservice/api/v1/public/newHomepage/category", function (dataJson) {
    util.request("/c2mwebservice/api/v1/public/newHomepage", function (dataJson) {
      console.log(dataJson)
      that.setData({
        dataJson: dataJson
      })
      console.log('获取首页所有数据' + that.data.dataJson)
      dataJson.returnData.scrollInfos.length = 3;
      dataJson.returnData.scrollInfos[0] = 
"https://source.magicmanufactory.com/html/redcollar/aboutus/images/banner1.jpg"  ;    
      dataJson.returnData.scrollInfos[1] = "https://source.magicmanufactory.com/html/redcollar/aboutus/images/banner1.jpg";
      dataJson.returnData.scrollInfos[2] = "https://source.magicmanufactory.com/html/redcollar/aboutus/images/banner1.jpg";
      // dataJson.returnData.scrollInfos[0].newsDesc = "../newMeasure/scroll5";
      // dataJson.returnData.scrollInfos[1].newsDesc = "../newMeasure/scroll2";
      // dataJson.returnData.scrollInfos[2].newsDesc = "../newMeasure/scroll4";
      // dataJson.returnData.scrollInfos[2].newsDesc = "../newMeasure/scroll4";
      //util.request("/c2mwebservice/api/v1/public/homepage", function (dataJson) {
      var windowWidth = app.globalData.deviceInfo.windowWidth / 5.5;
      //价格保留两位小数
      //dataJson.returnData.recommendGoods[3].recommendGoodsValue[0].goodsSellPrice
      dataJson.returnData.recommendGoods.forEach(function (element) {
        element.recommendGoodsValue.forEach(function (element2) {
          let tempPrice = parseFloat(element2.goodsSellPrice);
          tempPrice = tempPrice.toFixed(2);
          element2.goodsSellPrice = tempPrice;
        })
      })
      that.setData({
        width: `width: ${windowWidth}px;`,
        scrollY: true,
      })
      homedata = dataJson.returnData;
      that.setData({
        mdata: homedata
      })
      wx.setStorage({
        key: "homedata",
        data: dataJson.returnData
      });
    }, function (res) {
      wx.showToast({
        title: res.data.returnMsg,
        duration: 2000
      })
    });
    util.request("/c2mwebservice/api/v1/public/newHomepage/category", function (dataJson) {
      //util.request("/c2mwebservice/api/v1/public/homepage", function (dataJson) {
      homedataDategory = dataJson.returnData;
      that.setData({
        homedataDategory: homedataDategory
      })
      wx.setStorage({
        key: "homedataDategory",
        data: dataJson.returnData
      });

    }, function (res) {
      wx.showToast({
        title: res.data.returnMsg,
        duration: 2000
      })
    });
    //普通会员
    //    util.request("/c2mwebservice/api/v1/members/8a21ce6a55dba8cf0155dc91e16e0029/myWallet", function (dataJson) {
    //营销会员
    ///c2mwebservice/api/v1/marketingMembers/8a10a439514848fc0151485223b1002e/myWallet

    // util.request("/c2mwebservice/api/v1/marketingMembers/8a21ce6a55dba8cf0155dc91e16e0029/myWallet", function (dataJson) {
    // }, function (reason) {

    // });
    //请求首页数据
    //    util.getRegisterCode();
  },
  loadCity: function (latitude, longitude) {
    var page = this;
    wx.request({
      url: 'https://api.map.baidu.com/geocoder/v2/?ak=wMGn9dYvHQqpQ7ACPlfBDiF0oCcVi47n&coordtype=gcj02ll&location=' + latitude + ',' + longitude + '&output=json&pois=0',

      method: "get",
      success: function (res) {

        // console.logconsole.log(res.data.result.formatted_address)
        page.setData({
          city: res.data.result.formatted_address
        })

        wx.setStorageSync('location', res.data.result.formatted_address.substr(res.data.result.formatted_address.indexOf('市') + 1, 10))
      }
    })
  },

  onShow: function () {
    let list = new Array();
    let one = {
      'styleId': '1',
      'styleUrl': 'https://img.magicmanufactory.com/image/homePageNew/suteStyle/business.jpg',
      'categoryId': '26'
    };
    let two = {
      'styleId': '8',
      'styleUrl': 'https://img.magicmanufactory.com/image/homePageNew/suteStyle/Leisure.jpg',
      'categoryId': '26'
    }
    let three = {
      'styleId': '2',
      'styleUrl': 'https://img.magicmanufactory.com/image/homePageNew/suteStyle/Mix.jpg',
      'categoryId': '6'
    }
    let four = {
      'styleId': '3',
      'styleUrl': 'https://img.magicmanufactory.com/image/homePageNew/suteStyle/dressRecommand.jpg',
      'categoryId': '26'
    }
    list[0] = one;
    list[1] = two;
    list[2] = three;
    list[3] = four;

    this.setData({
      suitList: list
    })
  },
  onShareAppMessage: function () {//只有定义了此事件处理函数，右上角菜单才会显示 “转发” 按钮
    return {
      title: 'Cotte',
      desc: '酷特智能'
    }
  },
  //banner跳转网页
  goImgDec:function(e){
    var goToUrl = e.currentTarget.dataset.url
    console.log('banner图片地址')
    console.log(e.currentTarget.dataset.url)
    wx.navigateTo({
      url: '/pages/banner/banner?url=' + goToUrl,
    })

  },
  //悬浮框 手指触摸动作开始
  moveMeasureStart: function (e) {
    this.setData({
      scrollY: false
    })
  },
  //悬浮框 手指触摸后移动
  moveMeasure: function (e) {
    this.setData({
      movePosition: `left: ${e.changedTouches[0].pageX - 36}px; top: ${e.changedTouches[0].pageY - 36}px`
    })
  },
  //悬浮框 手指触摸动作结束
  moveMeasureEnd: function (e) {
    let left = (e.currentTarget.offsetLeft > app.globalData.deviceInfo.windowWidth / 2.0 - 36) ? app.globalData.deviceInfo.windowWidth - 16 - 72 : 16
    let top = e.changedTouches[0].pageY - 36
    if (top < 0) {
      top = 0
    } else if (top > app.globalData.deviceInfo.windowHeight - 72) {
      top = app.globalData.deviceInfo.windowHeight - 72
    }
    this.setData({
      movePosition: `left: ${left}px; top: ${top}px`,
      scrollY: true
    })
  },
  //悬浮框 单击时
  tapMeasure: function (e) {
    var system = getApp().globalData.deviceInfo.system;//手机系统版本
    var model = getApp().globalData.deviceInfo.model;//手机型号
    // debugger
    let mohuanUser = getApp().globalData.mohuanUser
    if (mohuanUser) {
     var  token = mohuanUser["X-AUTH-TOKEN"]
    }
    // debugger
    wx.checkSession({
     success: res =>{
       console.log('token可用')
     },
      fail: res => {
        console.log('token过期')
        wx.navigateTo({ url: '../login/login' })
      }
    })

    var temp = getApp().globalData.mohuanUser;
    if (temp == "" && temp == null && temp == undefined) {
      wx.showToast({
        title: '未登录',
      })
    }

    let that = this
    //预约量体登录验证  未登录跳转登录页
    if (!getApp().globalData.mohuanUser || !getApp().globalData.mohuanUser.memberId || getApp().globalData.mohuanUser.memberId.length == 0) {
      wx.navigateTo({ url: '../login/login' })
      return
    }

    // wx.showToast({ title: temps, icon: 'loading', uration: 20000 })
  
   
  //  获取量体订单列表

  wx.request({
    url: url + '/c2mwebservice/api/v2/members/' + getApp().globalData.mohuanUser.memberId + "/measureOrder/list?orderStatus=10004_10002_10003_10007_10008",
    method:'get',
    header:{
      'C2M-Identify': 'Platform: MiniProgram, APP Version:2.08  OS Version:' + system + ',Device Type:' + model,
      'Content-Encoding': 'gzip',
      'X-AUTH-TOKEN': token
    },
    success: res => {
      console.log('量体订单类列表')
      console.log(res)
      if(res.statusCode == '403'){
        wx.navigateTo({
          url: '../login/login',
        })
      }else{
        let dataArr = res.data.returnData
        if (dataArr.length == 0) {
          wx.navigateTo({
            url: '../newMeasure/newMeasure',
          })
        } else {
          let status = parseInt(dataArr[0].orderStatus)
          switch (status) {
            // case 10003: { wx.switchTab({ url: '../newMeasure/newMeasure' }) }
            case 10003: {
              wx.navigateTo({
                url: '../newMeasure/newMeasure',
              })
            }
            case 10002: {
              that.showHaveMeasureOrder('已成功预约', '请等待量体师与您联系', dataArr[0].orderId)
            }
              break
            case 10004:
            case 10007: {
              that.showHaveMeasureOrder('', `量体师--${dataArr[0].tailor.personName}即将为您服务!\n联系电话${dataArr[0].tailor.phoneNo}`, dataArr[0].orderId)
            }
              break
            case 10008: {
              that.showHaveMeasureOrder('', `量体师--${dataArr[0].tailor.personName}即将为您服务!\n联系电话${dataArr[0].tailor.phoneNo};\n预约量体时间${dataArr[0].appointTime}`)
            }
            default: {
              wx.navigateTo({
                url: '../newMeasure/newMeasure',
              })
            }
              break
          }
        }
      }
     
    }

  })

  },

  //取消量体预约
  showHaveMeasureOrder(title, message, orderId) {
    let showCancel = orderId ? true : false
    wx.showModal({
      title: title,
      content: message,
      cancelText: '取消预约',
      showCancel: showCancel,
      success: function (res) {
        if (!res.confirm) {
          wx.showToast({ title: 'loading..', icon: 'loading', uration: 20000 })
          util.postRequest(`/c2mwebservice/api/v1/members/${getApp().globalData.mohuanUser.memberId}/cancellation/measurements`,
            { "orderId": orderId, "cancelReasons": { "reasonId": 4, "reasonContent": "其他", "extraContent": "" } }, function (res) {
              wx.hideToast()
            }, function (res) {
              wx.hideToast()
            })
        }
      }
    })
  },
  bannerClick: function () {

    wx.navigateTo({
      url: '../newMeasure/scroll4'
    })


  },
  search: function () {
    wx.navigateTo({
      url: '../newsearch/newsearch'
    })
  }
})
